﻿using Autofac;
using CSRedis;
using Microsoft.AspNetCore.Mvc.Filters;
using SH.Common;
using SH.Common.CommonClass;
using SH.Common.DataDictionary;

using SH.Multitenant.Core.Saas;
using SqlSugar;



namespace SH.Multitenant.API.Filters
{
    /// <summary>
    /// 日志记录过滤器 
    /// </summary>
    public class LogActionFilter : Attribute, IActionFilter
    {
        /// <summary>
        /// 模块类型
        /// </summary>
        public string? Module { get; set; } = string.Empty;
        /// <summary>
        /// 方法内容
        /// </summary>
        public string? MethodContent { get; set; } = string.Empty;


        /// <summary>
        /// 构造方法
        /// </summary>

        /// <param name="methodContent">方法内容</param>
        public LogActionFilter(string? module, string? methodContent)
        {
            Module = module;
            MethodContent = methodContent;
        }
        /// <summary>
        /// 方法运行结束执行
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //var actionName = context.RouteData.Values["action"]!.ToString();
            //var controllerName = context.RouteData.Values["controller"]!.ToString();
            OperationLog ol = new OperationLog();
            var list = DbManger.BizDb.AsTenant().QueryableWithAttr<Dic>().AS("shmultitenantdb.dic").Where(x => x.Identification == "module").ToList();
            //添加操作日志
            CSRedisClient _redis = AppService.AutofacContainer.Resolve<CSRedisClient>();
            if (!string.IsNullOrEmpty(Module))
            {
                foreach (var item in list)
                {
                    if (Module.Contains(item.Value!))
                    {
                        ol.OperationName = _redis.Get<string>("uName");
                        ol.OperationModule = item.Sign;
                        ol.OperationTime = DateTime.Now;
                        ol.OperationContent = MethodContent;
                        ol.TenantId = _redis.Get<string>("tenantId");
                        DbManger.BizDb.Insertable<OperationLog>(ol).ExecuteCommand();
                        break;
                    }
                }
            }
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            //throw new NotImplementedException();
        }
    }
}
